//
//  DZOAuthViewController.m
//  Weico
//
//  Created by 大泽 on 15/7/21.
//  Copyright (c) 2015年 刘洪泽. All rights reserved.
//

#import "DZOAuthViewController.h"
#import <AFNetworking.h>
@interface DZOAuthViewController () <UIWebViewDelegate>

@end

@implementation DZOAuthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    UIWebView *webView = [[UIWebView alloc] init];
    webView.delegate = self;
    webView.frame = self.view.bounds;
    
    [self.view addSubview:webView];
    
    // https://api.weibo.com/oauth2/authorize
    
    /*
     请求参数client_id	true	string	申请应用时分配的AppKey。
     redirect_uri	true	string	授权回调地址，站外应用需与设置的回调地址一致，站内应用需填写canvas page的地址。
     */
    
    NSURL *url = [NSURL URLWithString:@"https://api.weibo.com/oauth2/authorize?client_id=2950921426&redirect_uri=http://www.baidu.com"];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [webView loadRequest:request];
}

- (void)webViewDidStartLoad:(UIWebView *)webView{
    
    DZLog(@"--------webViewDidStartLoad");
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    DZLog(@"-------webViewDidFinishLoad");
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    
    DZLog(@"%@", request.URL.absoluteString);
    
    NSString *url = request.URL.absoluteString;
    
    NSRange range = [url rangeOfString:@"code="];
    
    if (range.length) {
        
        NSString *code = [url substringFromIndex:range.location + range.length];
        NSLog(@"%@", code );

        [self getPostWithCode:code];
    }
    
    return YES;
}
- (void)getPostWithCode:(NSString *)code{
    
    
    /*
     https://api.weibo.com/oauth2/access_token
     client_id	true	string	申请应用时分配的AppKey。
     client_secret	true	string	申请应用时分配的AppSecret。
     grant_type	true	string	请求的类型，填写authorization_code
     
     grant_type为authorization_code时
     必选	类型及范围	说明
     code	true	string	调用authorize获得的code值。
     redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。
     
     */
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    mgr.responseSerializer = [AFJSONResponseSerializer serializer];

    NSMutableDictionary *parma = [NSMutableDictionary dictionary];
    parma[@"client_id"] = @"2950921426";
    parma[@"client_secret"] = @"008add77df911d145c0a82da836b45d6";
    parma[@"grant_type"] = @"authorization_code";
    parma[@"code"] = code;
    parma[@"redirect_uri"] = @"http://www.baidu.com";
    
    [mgr POST:@"https://api.weibo.com/oauth2/access_token" parameters:parma success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        DZLog(@"%@", responseObject);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        DZLog(@"%@", error);
    }];
}

@end
